let Node = require('./Node');

class LinkedList {

    constructor() {
        this.head = new Node("head");
    }

    /**
     * 查找节点
     * @param item
     * @private
     */
    _find(item) {
        let curNode = this.head;
        while (curNode.getValue() !== item) {
            curNode = curNode.getNext();
        }
        return curNode;
    }

    /**
     * 获取元素上一个节点
     * @param item
     * @returns {Node}
     * @private
     */
    _findPrev(item) {
        let curNode = this.head;

        while (curNode !== null && curNode.getNext().getValue() !== item) {
            curNode = curNode.next;
        }
        return curNode;
    }

    /**
     * 插入节点
     * @param newItem
     * @param item
     */
    insert(newItem, item) {
        let newNode = new Node(newItem), itemNode = this._find(item);
        newNode.setNext(itemNode.getNext());
        itemNode.setNext(newNode);
    }

    /**
     * 删除节点
     * @param item
     */
    remove(item) {
        let prevItem = this._findPrev(item), curNode = prevItem.next;

        prevItem.setNext(curNode.getNext());
    }

    /**
     * 展示链表结果
     */
    display() {
        let curNode = this.head;

        while (curNode.next !== null) {
            curNode = curNode.getNext();
            console.log(curNode.getValue());
        }

    }

}

let linkedList = new LinkedList();

linkedList.insert("金海宾", "head")
linkedList.insert("金海芳", "金海宾")
linkedList.insert("金梓轩", "金海芳")

linkedList.display();

linkedList.remove("金海芳");

linkedList.display();
